<template>
    <div>
        <div v-if="newsInfo" class="container">
            <h1>{{ newsInfo.title }}</h1>
            <div class="info">
                <span>{{ newsInfo.source }}</span>
                <span>{{ newsInfo.pubdate }}</span>
            </div>
            <div v-if="newsInfo.content" class="content" v-html="contentFormat(newsInfo.content)"></div>
            <div v-else class="content">
                <div class="photo-item" v-for="(item, i) in newsInfo.imageList" :key="i">
                    <img :src="item" width="100%"/>
                    <p>{{ newsInfo.textList[i] }}</p>
                </div>
            </div>
        </div>
        <div v-else class="loading">
            <Loading v-if="loadMore" color="#1989fa">加载中 . . .</Loading>
            <span v-else>没有更多数据了</span>
        </div>
        <Comment/>
    </div>
</template>

<script>
import { Loading } from 'vant';
import { getNewsInfo } from '@/services';
import Comment from '@/components/Comment';

export default {
    name: 'NewsInfo',
    components: { Loading, Comment },
    data() {
        return {
            newsInfo: null,
            loadMore: true
        };
    },
    methods: {
        // content 内容格式化
        contentFormat(content) {
            return content.replace(/(width="500" | alt)/g, 'width="100%"');
        }
    },
    created() {
        getNewsInfo(this.$route.params.type, this.$route.params.id)
            .then(newsInfo => this.newsInfo = newsInfo)
            .catch(err => {
                console.error('新闻详情获取失败', err.message);
                this.loadMore = false;
            });
    }
};
</script>

<style lang="less" scoped>
    .loading {
        display: flex;
        justify-content: center;
        margin-top: 100px;
    }
    .container {
        width: 100%;
        padding: 0 12px;
        box-sizing: border-box;
        margin-bottom: 20px;
        h1 {
            font-size: 24px;
        }
        .info {
            display: flex;
            justify-content: space-between;
            font-size: 14px;
            color: #999;
        }
        .content {
            line-height: 1.8em;
            font-size: 15px;
            .photo-item {
                margin-top: 1em;
                p {
                    margin: 0;
                    text-indent: 2em;
                }
            }
            img {
                width: 100%;
            }
        }
    }
</style>